<?php
namespace app\admin\controller;

use think\facade\Db;
use app\common\model\Goods as GoodsModel;
use app\common\model\GoodsCategory as CategoryModel;
use app\common\model\GoodsBrand as BrandModel;
use app\common\model\GoodsSpec as SpecModel;
use app\common\model\GoodsComment as CommentModel;
use app\common\model\GoodsType as TypeModel;
use app\common\model\ExpressShipping as ShippingModel;
/**
 * 商品控制器
 */
class Goods extends Admin 
{	
	/**
	 * 商品列表
	 * @return array
	 */
	public function index(){
		$title = $this->request->param('title/s');
		$status = $this->request->param('status/d');

		$where = [];
		$map = [];
		$query = [];
		if(!empty($title)){
			$where[] = ['title','like','%'.$title.'%'];
			$query['title'] = $title;
		}

		if(!empty($status)){
			$map['status'] = $status;
			$query['status'] = $status;
		}

		$list = GoodsModel::with('category')->where($map)->where($where)->order('id desc')->paginate(12, false, ['query' => $query]);

		$this->assign('list', $list);

		return $this->fetch();
	}

	/**
	 * 添加商品
	 */
	public function add(){
		if($this->request->isPost()){
			$data = $this->request->post();
			//验证
			$result = $this->validate($data,[
				'title|商品名称' => 'require',
				'cate|分类' => 'require',				
				'price|商品价格' => 'require',	
				'content|商品描述' => 'require'
			]);
			// 验证失败 输出错误信息
			if(true !== $result) $this->error($result);

			$sku_arr = [];
			if(!empty($data['sku'])){
				$sku_arr = json_decode($data['sku'], true);								
			}
			unset($data['sku']);
			$photo = $data['photo'];
			if(is_array($photo)){
				$data['photo'] = json_encode($photo);
				$data['thumb'] = $photo[0];
			}			

			if($res = GoodsModel::create($data)){
				if(is_array($sku_arr)){
					foreach ($sku_arr as $value) {
						$sku_data['goods_id'] = $res->id;
						$sku_data['spec_value'] = json_encode($value['ids']);
						$sku_data['price'] = $value['price'];
						$sku_data['stock'] = $value['stock'];
						$sku_data['goods_no'] = $value['sku'];
						$sku_data['create_time'] = request()->time();
						$sku_data['update_time'] = request()->time();
						Db::name('goods_sku')->insert($sku_data);
					}
				}
				$this->success('添加成功');
			}else{
				$this->error('添加失败');
			}
		}else{
			$category = CategoryModel::getList();
			$shipping = ShippingModel::where('status',1)->select();
			$types = TypeModel::where('status',1)->select();

			$this->assign('info', null);
			$this->assign('category', $category);
			$this->assign('shipping', $shipping);
			$this->assign('types',$types);

			return $this->fetch('edit');
		}
	}

	/**
	 * 编辑商品
	 */
	public function edit($id = 0){
		if($this->request->isPost()){
			$data = $this->request->post();

			//验证
			$result = $this->validate($data,[
				'title|商品名称' => 'require',
				'cate|分类' => 'require',				
				'price|商品价格' => 'require',	
				'content|商品描述' => 'require'
			]);
			// 验证失败 输出错误信息
			if(true !== $result) $this->error($result);			
			
			if(!empty($data['sku'])){
				$sku_arr = json_decode($data['sku'], true);
				Db::name('goods_sku')->where('goods_id',$data['id'])->delete();
				foreach ($sku_arr as $value) {
					$sku_data['goods_id'] = $data['id'];
					$sku_data['spec_value'] = json_encode($value['ids']);
					$sku_data['price'] = $value['price'];
					$sku_data['stock'] = $value['stock'];
					$sku_data['goods_no'] = $value['sku'];
					$sku_data['create_time'] = request()->time();
					$sku_data['update_time'] = request()->time();
					Db::name('goods_sku')->insert($sku_data);
				}				
			}
			unset($data['sku']);
			$photo = $data['photo'];
			if(is_array($photo)){
				$data['photo'] = json_encode($photo);
				$data['thumb'] = $photo[0];
			}

			if($res = GoodsModel::update($data)){
				$this->success('编辑成功');
			}else{
				$this->error('编辑失败');
			}
		}else{
			$category = CategoryModel::getList();
			$shipping = ShippingModel::where('status',1)->select();
			$types = TypeModel::where('status',1)->select();
			$info = GoodsModel::where('id',$id)->find();

			$spec_list = SpecModel::where(['type'=>$info['type'],'status'=>1])->order('sort asc')->select();
			$spec_data = [];
			foreach ($spec_list as $value) {
				$item['id'] = $value['id'];
				$item['name'] = $value['name'];
				$values = Db::name('goods_spec_value')->where(['spec_id'=>$value['id'],'status'=>1])->order('sort asc')->select();
				$value_data = [];
				foreach ($values as $v) {
					$vo['id'] = $v['id'];
					$vo['name'] = $v['name'];
					$value_data[] = $vo;
				}
				$item['sub'] = $value_data;
				$spec_data[] = $item;
			}
			
			$sku_list = Db::name('goods_sku')->where('goods_id',$info['id'])->select();
			$sku_data = [];
			if(empty($sku_list)){
				$sku_data = null;
			}else{
				foreach ($sku_list as $value) {
					$sku_item['ids'] = json_decode($value['spec_value'],true);
					$sku_item['price'] = $value['price'];
					$sku_item['stock'] = $value['stock'];
					$sku_item['sku'] = $value['goods_no'];
					$sku_data[] = $sku_item;
				}

				$sku_data = json_encode($sku_data);
			}

			$info['photo'] = json_decode($info['photo'],true);
			
			$this->assign('info', $info);
			$this->assign('spec_item', json_encode($spec_data));
			$this->assign('sku_data', $sku_data);
			$this->assign('category', $category);
			$this->assign('shipping', $shipping);
			$this->assign('types',$types);

			return $this->fetch();
		}
	}

	/**
	 * 删除商品
	 */
	public function del($id = 0){
		empty($id) && $this->error('参数错误');

		if(is_array($id)){
			$map[] = ['id','in',$id];
		}elseif(is_numeric($id)){
			$map[] = ['id','=',$id];
		}

		if($query = GoodsModel::where($map)->delete()){
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
	}

	/**
	 * 更新状态
	 * @return mixed
	 */
	public function update(){
		$data = $this->request->param();

		if(empty($data)){
			$this->error('参数错误');
		}	
		
		if($query = GoodsModel::update($data)){
			$this->success('更新成功');
		}else{
			$this->error('更新失败');
		}
	}

	/**
	 * 分类列表
	 * @return array
	 */
	public function category(){
		$list = CategoryModel::getList();

		$this->assign('list',$list);
		return $this->fetch();
	}

	/**
	 * 新增分类
	 * @param integer $pid 分类ID
	 */
	public function addCategory($pid = 0){
		if($this->request->isPost()){
			$data = $this->request->post();
			//验证
			$result = $this->validate($data,[
				'pid|父分类' => 'require',
				'name|分类名称' => 'require'
			]);
			// 验证失败 输出错误信息
			if(true !== $result) $this->error($result);

			if($query = CategoryModel::create($data)){
				$this->success('新增成功');
			}else{
				$this->error('新增失败');
			}
		}else{
			$plist = CategoryModel::getList();

			$this->assign('title', '新增分类');
			$this->assign('plist', $plist); 
			$this->assign('info',null);
			$this->assign('pid', $pid);

			return $this->fetch('editCategory');
		}
	}

	/**
	 * 编辑分类
	 * @param  integer $id 分类ID
	 * @return mixed
	 */
	public function editCategory($id = 0){
		if($this->request->isPost()){
			$data = $this->request->post();
			//验证
			$result = $this->validate($data,[
				'pid|父分类' => 'require',
				'name|分类名称' => 'require'
			]);
			// 验证失败 输出错误信息
			if(true !== $result) $this->error($result);

			if($query = CategoryModel::update($data)){
				$this->success('编辑成功');
			}else{
				$this->error('编辑失败');
			}
		}else{
			empty($id) && $this->success('参数错误');

			$info = CategoryModel::where('id',$id)->find();
			$plist = CategoryModel::getList();

			$this->assign('title', '编辑分类');
			$this->assign('plist', $plist); 
			$this->assign('info',$info);
			$this->assign('pid', $info['pid']);
			return $this->fetch('editCategory');
		}
	}

	/**
	 * 删除分类
	 * @param  integer $id 分类ID
	 * @return mixed
	 */
	public function delCategory($id = 0){
		empty($id) && $this->error('参数错误');

		if(is_array($id)){
			$map[] = ['id','in',$id];
		}elseif(is_numeric($id)){
			$map[] = ['id','=',$id];
		}

		if($query = CategoryModel::where($map)->delete()){
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
	}

	/**
	 * 更新状态
	 * @return mixed
	 */
	public function updateCategory(){
		$data = $this->request->param();

		if(empty($data)){
			$this->error('参数错误');
		}

		if($query = CategoryModel::update($data)){
			$this->success('更新成功');
		}else{
			$this->error('更新失败');
		}
	}

	/**
	 * 商品品牌
	 */
	public function brand(){
		$name = $this->request->param('name/s');
		$status = $this->request->param('status/d');

		$where = [];
		$map = [];
		$query = [];
		if(!empty($name)){
			$where[] = ['name','like','%'.$name.'%'];
			$query['name'] = $name;
		}

		if(!empty($status)){
			$map['status'] = $status;
			$query['status'] = $status;
		}

		$list = BrandModel::where($map)->where($where)->order('id desc')->paginate(15, false, ['query' => $query]);

		$this->assign('list', $list);
		return $this->fetch();
	}

	/**
	 * 添加商品品牌
	 */
	public function addBrand(){
		if($this->request->isPost()){
			$data = $this->request->post();
			//验证
			$result = $this->validate($data,[				
				'name|品牌名称' => 'require',
				'url|品牌链接' => 'require',
				'pic|品牌LOGO' => 'require'
			]);
			// 验证失败 输出错误信息
			if(true !== $result) $this->error($result);

			if($res = BrandModel::create($data)){
				$this->success('添加成功');
			}else{
				$this->error('添加失败');
			}
		}else{
			$this->assign('title', '新增品牌');
			$this->assign('info', null);
			return $this->fetch('editBrand');
		}
	}

	/**
	 * 编辑品牌
	 */
	public function editBrand($id = 0){
		if($this->request->isPost()){
			$data = $this->request->post();
			//验证
			$result = $this->validate($data,[				
				'name|品牌名称' => 'require',
				'url|品牌链接' => 'require',
				'pic|品牌LOGO' => 'require'
			]);
			// 验证失败 输出错误信息
			if(true !== $result) $this->error($result);

			if($res = BrandModel::update($data)){
				$this->success('编辑成功');
			}else{
				$this->error('编辑失败');
			}
		}else{
			empty($id) && $this->error('参数错误');

			$info = BrandModel::where('id',$id)->find();
			$this->assign('title', '编辑品牌');
			$this->assign('info', $info);

			return $this->fetch('editBrand');
		}
	}

	/**
	 * 删除品牌
	 */
	public function delBrand($id = 0){
		empty($id) && $this->error('参数错误');

		if(is_array($id)){
			$map[] = ['id','in',$id];
		}elseif(is_numeric($id)){
			$map[] = ['id','=',$id];
		}

		if($query = BrandModel::where($map)->delete()){
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
	}

	/**
	 * 更新状态
	 * @return mixed
	 */
	public function updateBrand(){
		$data = $this->request->param();

		if(empty($data)){
			$this->error('参数错误');
		}	
		
		if($query = BrandModel::update($data)){
			$this->success('更新成功');
		}else{
			$this->error('更新失败');
		}
	}

	/**
	 * 商品类型
	 * @return array
	 */
	public function type(){
		$name = $this->request->param('name/s');

		$map = [];
		$query = [];
		if(!empty($name)){
			$map[] = ['name','like','%'.$name.'%'];
			$query['name'] = $name;
		}

		$list = TypeModel::where($map)->order('id desc')->paginate(15, false, ['query' => $query]);

		$this->assign('list',$list);
		return $this->fetch();
	}

	/**
	 * 添加商品类型
	 */
	public function addType(){
		if($this->request->isPost()){
			$data = $this->request->post();
			//验证
			$result = $this->validate($data,[				
				'name|类型名称' => 'require'
			]);
			// 验证失败 输出错误信息
			if(true !== $result) $this->error($result);

			if($res = TypeModel::create($data)){
				$this->success('添加成功');
			}else{
				$this->error('添加失败');
			}
		}else{
			$this->assign('info', null);

			return $this->fetch('editType');
		}
	}

	/**
	 * 编辑商品类型
	 */
	public function editType($id = 0){
		if($this->request->isPost()){
			$data = $this->request->post();
			//验证
			$result = $this->validate($data,[				
				'name|类型名称' => 'require'
			]);
			// 验证失败 输出错误信息
			if(true !== $result) $this->error($result);

			if($res = TypeModel::update($data)){
				$this->success('编辑成功');
			}else{
				$this->error('编辑失败');
			}
		}else{
			empty($id) && $this->error('参数错误');

			$info = TypeModel::where('id',$id)->find();

			$this->assign('info',$info);
			return $this->fetch('editType');
		}
	}

	/**
	 * 删除商品类型
	 * @param  integer $id
	 * @return mixed
	 */
	public function delType($id = 0){
		empty($id) && $this->error('参数错误');

		if(is_array($id)){
			$map[] = ['id','in', $id];
		}elseif(is_numeric($id)){
			$map[] = ['id','=',$id];
		}

		if($query = TypeModel::where($map)->delete()){
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
	}

	/**
	 * 更新商品类型
	 */
	public function updateType(){
		$data = $this->request->param();

		if(empty($data)){
			$this->error('参数错误');
		}	
		
		if($query = TypeModel::update($data)){
			$this->success('更新成功');
		}else{
			$this->error('更新失败');
		}
	}

	/**
	 * 商品规格
	 */
	public function spec(){
		$name = $this->request->param('name/s');
		$map = [];
		$query = [];
		if(!empty($name)){
			$map[] = ['name','like','%'.$name.'%'];
			$query['name'] = $name;
		}

		$list = SpecModel::where($map)->order('id desc')->paginate(15, false, ['query' => $query]);
		foreach ($list as $key => $value) {
			$items = Db::name('goods_spec_value')->where('spec_id',$value['id'])->column('name');
			$list[$key]['items'] = implode(',', $items);
		}

		$this->assign('list', $list);
		return $this->fetch();
	}

	/**
	 * 添加商品规格
	 */
	public function addSpec(){
		if($this->request->isPost()){
			$data = $this->request->post();
			//验证
			$result = $this->validate($data,[				
				'name|品牌名称' => 'require',
				'type|规格分组' => 'require',
				'items|规格项' => 'require'
			]);
			// 验证失败 输出错误信息
			if(true !== $result) $this->error($result);			
			$items = explode(PHP_EOL, $data['items']);			
			unset($data['items']);

			if($res = SpecModel::create($data)){
				$dataItem = array();
				foreach ($items as $key => $value) {
					$value = str_replace('_', '', $value); // 替换特殊字符
            		$value = str_replace('@', '', $value); // 替换特殊字符
            		$value = trim($value);
            		$dataItem[] = array(
            			'spec_id' => $res->id,
            			'name' => $value,
            			'status' => 1,
            			'create_time' => time()
            		);
				}
				Db::name('goods_spec_value')->insertAll($dataItem);
				$this->success('添加成功');
			}else{
				$this->error('添加失败');
			}
		}else{
			$types = TypeModel::where('status',1)->select();

			$this->assign('info', null);
			$this->assign('types', $types);
			return $this->fetch('editSpec');
		}
	}

	/**
	 * 编辑商品规格
	 */
	public function editSpec($id = 0){
		if($this->request->isPost()){
			$data = $this->request->post();
			//验证
			$result = $this->validate($data,[				
				'name|规格名称' => 'require',
				'type|规格分组' => 'require',
				'items|规格项' => 'require'
			]);
			// 验证失败 输出错误信息
			if(true !== $result) $this->error($result);
			$id = $data['id'];
			$items = explode(PHP_EOL, $data['items']);
			unset($data['items']);

			if($res = SpecModel::update($data)){
				Db::name('goods_spec_value')->where('spec_id',$id)->delete();
				$dataItem = array();
				foreach ($items as $key => $value) {
					$value = str_replace('_', '', $value); // 替换特殊字符
            		$value = str_replace('@', '', $value); // 替换特殊字符
            		$value = trim($value);
            		$dataItem[] = array(
            			'spec_id' => $id,
            			'name' => $value,
            			'status' => 1,
            			'create_time' => time()
            		);
				}
				Db::name('goods_spec_value')->insertAll($dataItem);
				$this->success('编辑成功');
			}else{
				$this->error('编辑失败');
			}
		}else{
			empty($id) && $this->error('参数错误');

			$info = SpecModel::where('id',$id)->find();
			$items = Db::name('goods_spec_value')->where('spec_id',$id)->column('name');
			$info['items'] = implode(PHP_EOL,$items);
			$types = TypeModel::where('status',1)->select();

			$this->assign('info', $info);
			$this->assign('types', $types);

			return $this->fetch('editSpec');
		}
	}

	/**
	 * 删除商品规格
	 */
	public function delSpec($id = 0){
		empty($id) && $this->error('参数错误');

		if(is_array($id)){
			$map[] = ['id','in', $id];
		}elseif(is_numeric($id)){
			$map[] = ['id','=',$id];
		}

		if($query = SpecModel::where($map)->delete()){
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
	}

	/**
	 * 更新状态
	 * @return mixed
	 */
	public function updateSpec(){
		$data = $this->request->param();

		if(empty($data)){
			$this->error('参数错误');
		}	
		
		if($query = SpecModel::update($data)){
			$this->success('更新成功');
		}else{
			$this->error('更新失败');
		}
	}

	/**
	 * 商品评论
	 */
	public function comment(){
		$key = $this->request->param('key/s');
		$status = $this->request->param('status');

		$where = [];
		$map = [];
		$query = [];
		if(!empty($key)){
			$where[] = ['nickname','like','%'.$key.'%'];
			$query['key'] = $key;
		}

		if(!empty($status)){
			$map['status'] = $status;
			$query['status'] = $status;
		}
		
		$list = CommentModel::with('goods')->where($map)->where($where)->order('id desc')->paginate(15, false, ['query' => $query]);

		$this->assign('list', $list);
		return $this->fetch();
	}

	/**
	 * 获取规格JSON数据
	 * @return json
	 */
	public function getAjaxSpec($type = 0){
		if($type <= 0){
			return json(['code' => 0, 'msg' => '参数错误']);
		}

		$list = SpecModel::where(['type'=>$type,'status'=>1])->order('sort asc')->select();
		$data = [];
		foreach ($list as $value) {
			$item['id'] = $value['id'];
			$item['name'] = $value['name'];
			$values = Db::name('goods_spec_value')->where(['spec_id'=>$value['id'],'status'=>1])->order('sort asc')->select();
			$value_data = [];
			foreach ($values as $v) {
				$vo['id'] = $v['id'];
				$vo['name'] = $v['name'];
				$value_data[] = $vo;
			}
			$item['sub'] = $value_data;
			$data[] = $item;
		}

		return json(['code' => 1, 'data' => $data]);
	}

	public function upload(){
		return $this->fetch();
	}
}